<template>
  <div class="system-dict-container">
    <!-- 搜索区域 -->
    <div class="search-wrapper">
      <el-form :inline="true">
        <el-form-item label="字典名称">
          <el-input
            v-model="queryParams.baseSystemDictQueryVo.name"
            placeholder="请输入字典名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="字典类型名称">
          <el-input
            v-model="queryParams.baseSystemDictQueryVo.typeName"
            placeholder="请输入字典类型名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button-group>
            <el-button
              type="primary"
              :icon="Search"
              @click="handleSearch"
            >
              {{ t('table.search') }}
            </el-button>
            <el-button
              :icon="Refresh"
              class="reset-button"
              @click="handleReset"
            >
              {{ t('table.reset') }}
            </el-button>
          </el-button-group>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作区域 -->
    <div class="operation-wrapper">
      <el-button-group>
        <el-button
          type="primary"
          :icon="Plus"
          @click="handleAdd"
        >
          {{ t('table.add') }}
        </el-button>
      </el-button-group>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      style="width: 100%"
      height="calc(100vh - 220px)"
    >
      <el-table-column
        prop="name"
        label="字典名称"
        min-width="120"
      />
      <el-table-column
        prop="value"
        label="字典编码"
        min-width="120"
      />
      <el-table-column
        prop="typeName"
        label="字典类型名称"
        min-width="120"
      />
      <el-table-column
        prop="type"
        label="字典类型编码"
        min-width="120"
      />
      <el-table-column
        prop="parentValue"
        label="父级编码"
        min-width="120"
      />
      <el-table-column
        prop="status"
        label="状态"
        width="66"
      >
        <template #default="{ row }">
          <el-switch
            :model-value="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="(val) => handleStatusChange(row, val)"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="160"
      />
      <el-table-column
        :label="t('table.operation')"
        width="210"
        fixed="right"
      >
        <template #default="{ row }">
          <el-button-group>
            <el-button
              type="primary"
              link
              :icon="View"
              @click="handleDetail(row)"
            >
              {{ t('table.detail') }}
            </el-button>
            <el-button
              type="primary"
              link
              :icon="Edit"
              @click="handleEdit(row)"
            >
              {{ t('table.edit') }}
            </el-button>
            <el-button
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(row)"
            >
              {{ t('table.delete') }}
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 抽屉表单 -->
    <drawer-form
      v-model="drawer.visible"
      :title="drawer.title"
      :loading="drawer.loading"
      :rules="drawer.type === 'detail' ? {} : rules"
      :readonly="drawer.type === 'detail'"
      :data="formData"
      @submit="handleSubmit"
    >
      <el-form-item
        label="字典名称"
        prop="name"
      >
        <el-input
          v-model="formData.name"
          placeholder="请输入字典名称"
        />
      </el-form-item>
      <el-form-item
        label="字典编码"
        prop="value"
      >
        <el-input
          v-model="formData.value"
          placeholder="请输入字典编码"
        />
      </el-form-item>
      <el-form-item
        label="字典类型名称"
        prop="typeName"
      >
        <el-input
          v-model="formData.typeName"
          placeholder="请输入字典类型名称"
        />
      </el-form-item>
      <el-form-item
        label="字典类型编码"
        prop="type"
      >
        <el-input
          v-model="formData.type"
          placeholder="请输入字典类型编码"
        />
      </el-form-item>
      <el-form-item
        label="父级编码"
        prop="parentValue"
      >
        <el-input
          v-model="formData.parentValue"
          placeholder="请输入父级编码"
        />
      </el-form-item>
      <el-form-item
        label="状态"
        prop="status"
      >
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">{{ t('dict.enable') }}</el-radio>
          <el-radio :label="0">{{ t('dict.forbid') }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </drawer-form>
  </div>
</template>

<script setup lang="ts">
  import { API_URLS } from '@/base/interface-config';
  import { axiosRequest } from '@/utils/http-service';
  import { Delete, Edit, Plus, Refresh, Search, View } from '@element-plus/icons-vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { reactive, ref } from 'vue';
  import { useI18n } from 'vue-i18n';
  // 查询参数
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    orderBy: 'create_time desc',
    baseSystemDictQueryVo: {
      name: '',
      typeName: ''
    }
  });

  // 表格数据
  const tableData = ref([]);
  const total = ref(0);
  const loading = ref(false);

  // 抽屉表单
  const drawer = reactive({
    visible: false,
    title: '',
    loading: false,
    type: '' // 新增: add, 编辑: edit, 详情: detail
  });

  // 表单数据
  const formData = reactive({
    dataDictId: '',
    name: '',
    value: '',
    parentValue: '',
    type: '',
    typeName: '',
    status: 1
  });

  // 表单校验规则
  const rules = {
    name: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
    value: [{ required: true, message: '请输入字典编码', trigger: 'blur' }],
    typeName: [{ required: true, message: '请输入字典类型名称', trigger: 'blur' }],
    type: [{ required: true, message: '请输入字典类型编码', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }]
  };
  const { t } = useI18n();

  // 获取表格数据
  const getTableData = async () => {
    try {
      loading.value = true;
      const res = await axiosRequest({
        url: API_URLS.baseSystemDict.list,
        data: queryParams
      });
      if (res.data.operateSuccess) {
        tableData.value = res.data.baseSystemDictQueryVos;
        total.value = res.data.totals;
      }
    } catch (error) {
      console.error('获取系统字典列表失败:', error);
    } finally {
      loading.value = false;
    }
  };

  // 搜索
  const handleSearch = () => {
    queryParams.pageNum = 1;
    getTableData();
  };

  // 重置
  const handleReset = () => {
    queryParams.baseSystemDictQueryVo.name = '';
    queryParams.baseSystemDictQueryVo.typeName = '';
    handleSearch();
  };

  // 新增
  const handleAdd = () => {
    drawer.type = 'add';
    drawer.title = '新增系统字典';
    drawer.visible = true;
    Object.assign(formData, {
      dataDictId: '',
      name: '',
      value: '',
      parentValue: '',
      type: '',
      typeName: '',
      status: 1
    });
  };

  // 编辑
  const handleEdit = async (row: any) => {
    try {
      const res = await axiosRequest({
        url: API_URLS.baseSystemDict.findById,
        data: {
          baseSystemDictQueryVo: {
            dataDictId: row.dataDictId
          }
        }
      });
      if (res.data.operateSuccess) {
        drawer.type = 'edit';
        drawer.title = '编辑系统字典';
        drawer.visible = true;
        Object.assign(formData, res.data.baseSystemDictQueryVo);
      }
    } catch (error) {
      console.error('获取系统字典详情失败:', error);
    }
  };

  // 详情
  const handleDetail = async (row: any) => {
    try {
      const res = await axiosRequest({
        url: API_URLS.baseSystemDict.findById,
        data: {
          baseSystemDictQueryVo: {
            dataDictId: row.dataDictId
          }
        }
      });
      if (res.data.operateSuccess) {
        drawer.type = 'detail';
        drawer.title = '系统字典详情';
        drawer.visible = true;
        Object.assign(formData, res.data.baseSystemDictQueryVo);
      }
    } catch (error) {
      console.error('获取系统字典详情失败:', error);
    }
  };

  // 删除
  const handleDelete = (row: any) => {
    ElMessageBox.confirm('确认删除该系统字典吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        const res = await axiosRequest({
          url: API_URLS.baseSystemDict.delete,
          data: {
            baseSystemDictModifyVo: {
              dataDictId: row.dataDictId
            }
          }
        });
        if (res.data.operateSuccess) {
          ElMessage.success('删除成功');
          getTableData();
        }
      } catch (error) {
        console.error('删除系统字典失败:', error);
      }
    });
  };

  // 状态变更
  const handleStatusChange = async (row: any, value: string | number | boolean) => {
    try {
      const updateData = {
        ...row,
        status: value
      };
      Object.assign(formData, updateData);
      await handleSubmit();
    } catch (error) {
      // 如果更新失败，回滚状态
      row.status = row.status === 1 ? 0 : 1;
      console.error('状态更新失败:', error);
    }
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      drawer.loading = true;
      const url = drawer.type === 'add' ? API_URLS.baseSystemDict.save : API_URLS.baseSystemDict.update;
      const res = await axiosRequest({
        url,
        data: {
          baseSystemDictModifyVo: formData
        }
      });
      if (res.data.operateSuccess) {
        ElMessage.success(drawer.type === 'add' ? '新增成功' : '更新成功');
        drawer.visible = false;
        getTableData();
      }
    } catch (error) {
      console.error(drawer.type === 'add' ? '新增系统字典失败:' : '更新系统字典失败:', error);
    } finally {
      drawer.loading = false;
    }
  };

  // 分页大小变更
  const handleSizeChange = (val: number) => {
    queryParams.pageSize = val;
    getTableData();
  };

  // 当前页变更
  const handleCurrentChange = (val: number) => {
    queryParams.pageNum = val;
    getTableData();
  };

  // 初始化加载数据
  onMounted(() => {
    getTableData();
  });
</script>

<style lang="scss" scoped>
  .system-dict-container {
    padding: 16px;
    background: #fff;
    border-radius: 4px;
    position: relative;

    .search-wrapper {
      margin-bottom: 16px;

      :deep(.el-form) {
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        .el-form-item {
          margin-bottom: 8px;
          margin-right: 16px;
        }
      }
    }

    .operation-wrapper {
      margin-bottom: 16px;
      text-align: right;
      width: 100%;
      margin-top: -56px;
    }

    .pagination-container {
      position: fixed;
      left: 216px;
      right: 16px;
      bottom: 16px;
      display: flex;
      justify-content: center;
      padding: 16px 0;
      background: #fff;
      z-index: 10;
    }
  }

  :deep(.el-table th.el-table__cell) {
    background: #fff7e5;
  }

  :deep(.el-table) {
    border: none;
    th.el-table__cell,
    td.el-table__cell {
      border: none;
      border-bottom: 1px solid #f2f2f2;
    }
  }
</style>
